import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getTimeout } from '@/utils/auth'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
  // timeout: 5000
})

const iftime = () => {
  const oldtime = getTimeout('timeout')
  const newtime = Date.now()
  return (newtime - oldtime) >= 1000 * 60 * 60
}
// request interceptor
service.interceptors.request.use(config => {
  if (store.getters.token) {
    if (iftime()) {
      store.dispatch('user/logout')
      router.push({
        path: '/login'
      })
      return Promise.reject(Message.error('登录超时'))
    }
    config.headers.Authorization = 'Bearer ' + store.getters.token
  }
  return config
}, error => {
  return Promise.reject(Message.error(error.message))
})

// 响应拦截器
service.interceptors.response.use(res => {
  const { success, message } = res.data
  if (success) {
    return res.data
  } else {
    return Promise.reject(Message.error(message))
  }
}, error => {
  if (error.response && error.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push({
      path: '/login'
    })
    return Promise.reject(Message.error('登录超时'))
  }
  return Promise.reject(Message.error(error.message))
})

export default service
